<?php

namespace App\Jobs;

use App\Models\Championship;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ChampionshipNotice implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $championship;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Championship $championship)
    {
        $this->championship = $championship;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //查询收件人邮箱
        $userModel = config('admin.database.users_model');
        $userModel = new $userModel();

        $city = $this->championship->city;
        $email = $this->getEmail($userModel, $city);
        if ($email != "") {
            //发送邮件
            $title = $this->championship->title;
            $msg = "有人申请发布赛事，赛事名称【 $title 】。请及时处理!";
            \Mail::raw($msg, function ($message) use ($email) {
                $message->to($email);
                $message->subject('赛事申请提醒');
            });
        }

    }

    public function getEmail($userModel, $city)
    {
        $city = substr($city . '000000', 0, 6);
        $user = $userModel::where('city', $city)->first();
        if ($user && !empty($user->email)) {
            return $user->email;
        }
        if ($city == '000000') {
            return "";
        }

        $city = rtrim($city, '0');
        if (strlen($city) % 2 === 1) {
            $city = $city . '0';
        }
        $city = substr($city, 0, -2);

        return $this->getEmail($userModel, $city);
    }
}
